package com.itheima.springbootwebtlias.filter;

import com.itheima.springbootwebtlias.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String Url = request.getRequestURL().toString();

        if(Url.contains("/login")){
            log.info("亲爱的业主，我来带您办理门禁卡");
            filterChain.doFilter(request, response);
            return;
        }


        String token = request.getHeader("token");
        if(token == null){
            log.info("你没有登录进来干什么？？\n 登录去吧！！");

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);



            return;
        }


        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌解析错误，登录去吧！！");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }


        log.info("欢迎业主回家！！");
        filterChain.doFilter(request, response);





    }
}
